package com.tgy;

/**
 * @Author: tgy
 * @Date: 2020-10-19 09:15
 */
public class CountingSort extends Sort<Integer> {

    @Override
    protected void sort() {

        int min = Integer.MAX_VALUE,max = Integer.MIN_VALUE;

        for (Integer element : elements) {

            if (element < min) {

                min = element;
            }

            if (element > max) {

                max = element;
            }
        }

        // int 默认初始化为 0
        int[] countArr = new int[max - min + 1];


        for (Integer element : elements) {

            countArr[element - min]++;
        }

        int index = 0;
        for (int i = 0; i < countArr.length; i++) {

            while (countArr[i] > 0) {

                elements[index++] = i + min;
                countArr[i]--;
            }
        }
    }
}

